﻿using System.Web.Helpers;
using System.Web.Mvc;

using Web.Infrastructure.Grid;

namespace Web.Infrastructure
{
    /// <summary>
    /// Sets default values for the MvcContrib grid based listing actions.
    /// </summary>
    /// <remarks>
    /// Uses the following naming convention:
    ///  - page size parameter name: size
    ///  - page index parameter name: page
    ///  - sort options parameter name: sort
    /// </remarks>
    public sealed class ListingActionAttribute : ActionFilterAttribute
    {
        private readonly string _defaultSortColumn;

        private readonly int _defaultPageSize;

        /// <summary>
        /// Initializes a new instance of the <see cref="ListingActionAttribute"/> class.
        /// </summary>
        /// <param name="defaultSortColumn">The default sort column.</param>
        /// <param name="defaultPageSize">Default size of the page.</param>
        public ListingActionAttribute(string defaultSortColumn, int defaultPageSize = 10)
        {
            _defaultSortColumn = defaultSortColumn;
            _defaultPageSize = defaultPageSize;
        }

        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (null == filterContext.ActionParameters["size"] || (int)filterContext.ActionParameters["size"]<1)
                filterContext.ActionParameters["size"] = _defaultPageSize;
            if ((null == filterContext.ActionParameters["page"]) || ((int)filterContext.ActionParameters["page"]<1))
                filterContext.ActionParameters["page"] = 1;

            GridSortOptions sortOptions = (GridSortOptions)filterContext.ActionParameters["sort"];
            if (string.IsNullOrEmpty(sortOptions.Column))
            {
                sortOptions.Column = _defaultSortColumn;
                sortOptions.Direction = SortDirection.Ascending;
            }

            base.OnActionExecuting(filterContext);
        }
    }
}